package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //1. 获取过去五天的时间
        Date date = DateTime.now().minusDays(15).toDate();

        //2. 查询过去五天发布的所有的文章数据
        List<ApArticle> apArticleList = apArticleMapper.findArticleListByDays(date);

        //3. 根据规则计算每篇文章的得分
        List<HotArticleVo> hotArticleList = computeArticleScore(apArticleList);

        //4. 把得分最高的30行记录缓存到各个频道和推荐中
        cacheTagToRedis(hotArticleList);
    }

    /**
     * 缓存数据到redis
     * @param hotArticleList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleList) {
        //1. 查询所有的频道
        ResponseResult responseResult = wemediaClient.findAll();
        if(responseResult.getCode() == 200){
            //2. 解析所有的频道数据
            String json = JSON.toJSONString(responseResult.getData());
            List<WmChannel> channelList = JSON.parseArray(json, WmChannel.class);
            //3. 查找某一个频道下的所有的文章数据
            for (WmChannel wmChannel : channelList) {
                List<HotArticleVo> channelData = hotArticleList.stream()
                        .filter(item -> item.getChannelId() == wmChannel.getId()).collect(Collectors.toList());

                //4. 对频道内的文章进行排序
                channelData = channelData.stream()
                        .sorted(Comparator.comparing(HotArticleVo::getScore)
                                .reversed()).limit(30).collect(Collectors.toList());

                //5. 把数据缓存到redis
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId(), JSON.toJSONString(channelData));
            }

            //6. 缓存推荐数据
            hotArticleList = hotArticleList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore)
                            .reversed()).limit(30).collect(Collectors.toList());
            cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG, JSON.toJSONString(hotArticleList));
        }
    }

    /**
     * 计算文章的得分
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> apArticleList) {
        if(!apArticleList.isEmpty()){
            List<HotArticleVo> voList = new ArrayList<>(apArticleList.size());

            for (ApArticle apArticle : apArticleList) {
                HotArticleVo vo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, vo);
                vo.setScore(compute(apArticle));

                voList.add(vo);
            }

            return voList;
        }

        return new ArrayList<>();
    }

    // 得分具体的算法
    private Integer compute(ApArticle apArticle) {
        Integer score = 0;

        if(apArticle.getLikes() != null){
            score += apArticle.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }

        if(apArticle.getComment() != null){
            score += apArticle.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        if(apArticle.getCollection() != null){
            score += apArticle.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
